/*
 * @Descripttion: 描述
 * @Author: 刘黎
 * @Date: 2024-07-03 13:33:39
 * @LastEditors: 刘黎
 * @LastEditTime: 2024-08-19 14:53:13
 */
import axios from 'axios'
import { ElMessage } from 'element-plus'
import { useUserInfoStore } from '@/store/index.js';
import router from "@/router/index.js"


axios.defaults.timeout = 1200000 // 超时时间
// axios.defaults.baseURL = 'http://106.75.35.198/admin' //开发
axios.defaults.baseURL = 'https://www.strendystone.com/admin' //正式


// 请求拦截器
axios.interceptors.request.use(async config => {
  if(useUserInfoStore().userInfo){
    config.headers.token = useUserInfoStore().userInfo.token;
  }
  return config
}, error => {
  return Promise.reject(error.response) //请求错误时通过该方法返回配置信息
})

// 响应拦截器
axios.interceptors.response.use(
  response => {
    // console.log(response);
    if (response.data.code == 1) {//成功
      if(response.data.data.code === 30002){//账号过期
        ElMessage.error(response.data.data.message);
        return Promise.reject(response)
      } else {
        return Promise.resolve(response)
      }
    } else if(response.data.code == 10006){//登录过期
      ElMessage.error(response.data.message);
      router.push('/login'); // 跳转到名为 "home" 的路由
      return Promise.reject(response); //失败
    } else {
      ElMessage.error(response.data.msg)
      return Promise.reject(response); //失败
    }
  },
  error => {
    //console.log(error);
    if (error.code === 'ECONNABORTED' || error.message === "Network Error" || error.message.includes("timeout")) {
      //网络超时异常处理
    }
    return Promise.reject(error.response);
  }
)

// 封装get方法
export const get = (url, params) => {
  return new Promise((resolve, reject) => {
    axios.get(url, { params: params }).then(res => {
      resolve(res.data);
    }).catch(err => {
      reject(err.data)
    })
  });
}

// 封装post请求
export const post = (url, params) => {
  return new Promise((resolve, reject) => {
    axios.post(url,  params ).then(res => {
      resolve(res.data);
    }).catch(err => {
      reject(err)
    })
  });
}

export default axios
